package com.wuhan.template.module.home.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.wuhan.template.R;
import com.wuhan.template.base.BaseFragment;
import com.wuhan.template.constant.Urls;
import com.wuhan.template.module.home.adapter.DianShiBaseAdapter;
import com.wuhan.template.module.home.entity.DianShiEntity;
import com.wuhan.template.utils.EventMessage;
import com.wuhan.template.utils.OkHttpUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2016/5/12 0012.
 */
public class DianShiFragment extends BaseFragment {

    @BindView(R.id.dianshi_pullListView)
    protected PullToRefreshListView listView;
    private DianShiBaseAdapter dianShiBaseAdapter;

    public DianShiFragment() {

    }

    @Override
    protected void initViews() {
        dianShiBaseAdapter = new DianShiBaseAdapter(getContext(), dianShiLists);
        listView.setAdapter(dianShiBaseAdapter);

        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                dianShiLists.clear();
                loadData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_dianshi;
    }

    public static DianShiFragment newInstance() {

        Bundle args = new Bundle();

        DianShiFragment fragment = new DianShiFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void loadData() {

        OkHttpUtils.get(Urls.DIANSHI, null);
    }

    private List<DianShiEntity> dianShiLists = new ArrayList<>();

    @Override
    protected void postEventResult(@NonNull EventMessage message) {
        if (Urls.DIANSHI.equals(message.type)) {
            Gson gson = new Gson();
            DianShiEntity[] dianShiEntities = gson.fromJson(message.result, DianShiEntity[].class);

            dianShiLists.addAll(Arrays.asList(dianShiEntities));

            dianShiBaseAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}

